package it.polimi.registration.business.security.entity;

import it.polimi.registration.business.security.control.PasswordEncrypter;

import java.io.Serializable;
import java.net.URI;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

@Entity(name = "user")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="TYPE_ENTITE")
public class AbstractUser implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private int id;
	
	@Pattern(regexp = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?",
            message = "invalid email")
    @NotNull(message = "May not be empty")
	@Column(name = "USERNAME", unique = true)
	private String emailAddress;
	
    @NotNull(message = "May not be empty")
	private String password;
    
    @NotNull(message = "May not be empty")
    private String groupName;
	
	private URI avatar;
	
	public AbstractUser() {
		this.avatar = null;
	}
	
	public AbstractUser(String emailAddress, String password, URI avatar) {
		this.emailAddress = emailAddress;
		this.password = password;
		this.avatar = avatar;
	}
	
	public URI getAvatar() {
		return avatar;
	}
	
	public String getEmailAddress() {
		return emailAddress;
	}
	
	public void setEmailAddress(String emailAddress) {
		this.emailAddress = emailAddress;
	}
	
	public int getId() {
		return id;
	}
	
	public String getPassword() {
		return password;
	}

    public void setPassword(String password) {
        this.password = PasswordEncrypter.encryptPassword(password);
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public String getGroupName() {
        return groupName;
    }
    
    @Override
    public boolean equals(Object obj) {
    	if(super.equals(obj))
    		return true;
    	if(!(obj instanceof AbstractUser))
    		return false;
    	
    	User u = (User) obj;
    	return this.getId() == u.getId();
    }
}